﻿'Imports System.Web.UI.WebControls
'Imports System.Web.UI.WebControls.WebParts
'Imports System.Web.UI.HtmlControls
Imports ADOEntity
Imports System.IO
Imports System.Data
Imports System.Xml
Imports System.Xml.Serialization
Imports System.Globalization
Imports System.Data.OleDb
Imports System.Data.Odbc
Imports System.Threading
Imports DevExpress.Web.ASPxUploadControl
Imports clsDateFormat


Partial Class Administrator_frmImportData
    Inherits Web.UI.BasePage

#Region "Valiable"
    Private Enum chkStatus
        CountUploadFile
        UploadFile
        CanCel
    End Enum

    'Private Const pathDriveOnServer As String = "K:\\"
    Private PathFileOnServer As String = ""
    Private PathFileBackupOnServer As String = ""
    Private Const PathTextReadPathShare As String = "\\lib\\Data\\Folder_Share.txt"
    Private Const PathTextReadPathFuzzy As String = "\\lib\\Data\\NameTaskFuzzy.txt"
    Private Const pathSanctionListOnServer As String = "\\Sanction_list\\"
    Private Const pathSanctionListLogOnServer As String = "\\Sanction_list_log\\"
    Private Const pathSanctionListBackOnServer As String = "\\sanction_list_back\\"
    Private Const PathFileFloderBatch As String = "\\Sanction_List_Batch\\RunTask.txt"
    Private Const PathFileFloderBatchTest As String = "\\Sanction_List_Batch\\RunSanctionList.bat"
    Private Const NameFileTest As String = "_Test"
    Dim pathDriveOnServer As String = ""
    Dim fullUploadPath As String = ""
    Dim convertDate As clsDateFormat
    Dim clsSessionMenuRight As clsSessionMenuRight = New clsSessionMenuRight
    Dim clsDatabase As clsDatabase
    Dim SanctionEntity As SanctionEntities
    Dim SanctionListNewEntity As ADOEntitySanctionList.SanctionListEntities
    Dim sactionListMapper As SanctionListMapping2DB
    Dim dsForShow As DataSet


    Dim strFileName As String = ""
    Dim strFileType As String = ""
    Dim strBatchTestJob As String = ""
    Dim strFileTypeCode As String = ""
    Dim strListFileTypeCode As String = ""
    Dim infoSource As String = ""

#End Region


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            PathFileOnServer = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings("Path_KYC_SANCTION_LIST"))
            PathFileBackupOnServer = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings("Path_KYC_SANCTION_LIST_BAK"))

            btnTestUpload.Attributes.Add("onclick", "NoDoubleSubmit(); ")
            btnUpload.Attributes.Add("onclick", "NoDoubleSubmit();")

            'btnDelete.Attributes.Add("onclick", "NoDoubleSubmit();")
            btnDelete.Attributes.Add("onclick", " var rValue = confirm('ยืนยันการลบข้อมูล'); if (rValue == true){ NoDoubleSubmit();} ")
            sactionListMapper = New SanctionListMapping2DB
            SanctionListNewEntity = New ADOEntitySanctionList.SanctionListEntities
            clsSessionMenuRight = Session("ClsMenuRight")
            If Not IsPostBack Then
                chkIsLogin()
                CreateControlMP()
                'LoadSanctionList()
                loadDataToDropDown()
                convertDate = New clsDateFormat
                txtDate.Text = convertDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.Th, Now.Date)
                convertDate = Nothing

                ' txtOther.Visible = False

            End If


            If hdfCountRow.Value = "" Then
                btnUpload.Enabled = False
            Else
                btnUpload.Enabled = True
            End If

        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, _
                                                            Me.GetType(), _
                                                            "clientScript", _
                                                            "alert('" + ex.Message.Replace("'", "") + "')", _
                                                            True)

        End Try
    End Sub

    Protected Sub btnTestUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnTestUpload.Click

        Try
            ' Server.

            'pathDriveOnServer = readfile(System.Web.HttpContext.Current.Server.MapPath("~") & PathTextReadPathShare)
            'DeleteFileInDirectory(pathDriveOnServer & pathSanctionListOnServer)
            'DeleteFileInDirectory(pathDriveOnServer & pathSanctionListLogOnServer)

            If FileUpload1.PostedFile.ContentLength = 0 Then
                ScriptManager.RegisterStartupScript(Me, _
                                                              Me.GetType(), _
                                                              "clientScript", _
                                                              "alert('กรุณาเลือกไฟล์ที่ต้องการอัพโหลด')", _
                                                              True)
            ElseIf ddlList.SelectedIndex = 0 Then
                ScriptManager.RegisterStartupScript(Me, _
                                                            Me.GetType(), _
                                                            "clientScript", _
                                                            "alert('กรุณาเลือกประเภท')", _
                                                            True)
                'ElseIf ddlList.SelectedValue = "99" And txtOther.Text.Trim = "" Then
                '    ScriptManager.RegisterStartupScript(Me, _
                '                                             Me.GetType(), _
                '                                             "clientScript", _
                '                                             "alert('กรุณาตั้งชื่อประเภทอื่นๆ')", _
                '                                             True)
            Else

                SanctionEntity = New SanctionEntities
                Dim SanctionList = (From tblSanctionList In SanctionEntity.MSANCTIONLIST _
                                    Where tblSanctionList.LISTTYPECODE = ddlList.SelectedValue _
                                    Select tblSanctionList.LISTTYPECODE, tblSanctionList.LISTTYPENAME, _
                                            tblSanctionList.FILENAME, tblSanctionList.BATCHJOB, tblSanctionList.BATCHTESTJOB, tblSanctionList.FILETYPE).ToList



                strFileName = SanctionList(0).FILENAME
                strBatchTestJob = SanctionList(0).BATCHTESTJOB
                strFileType = SanctionList(0).LISTTYPENAME
                strFileTypeCode = SanctionList(0).FILETYPE
                strListFileTypeCode = SanctionList(0).LISTTYPECODE

                fullUploadPath = ""
                uploadFileToServer(strFileName)
                hdfmsg.Value = fullUploadPath
                hdfSanctionCode.Value = strFileTypeCode
                hdfSanctionTypeCode.Value = strListFileTypeCode
                hdfSanctionFileType.Value = strFileType
                hdfUpload.Value = FileUpload1.Value

                statusUpload(1)
                btnCancel.Enabled = False

                ScriptManager.RegisterStartupScript(Me, _
                                                        Me.GetType(), _
                                                        "clientScript", _
                                                        "NoDoubleSubmit2();", _
                                                        True)

                ' Ball V-Smart
                'continue at hdfButton_Click ,Use this trick this because prevent stopping loading gif image from postback

            End If



        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, _
                                                         Me.GetType(), _
                                                         "clientScript", _
                                                         "alert('" + ex.Message + "')", _
                                                         True)

        End Try
    End Sub

    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        Try

            pathDriveOnServer = readfile(System.Web.HttpContext.Current.Server.MapPath("~") & PathTextReadPathShare)
            'DeleteFileInDirectory(pathSanctionListOnServer)
            DeleteFileInDirectory(pathDriveOnServer & pathSanctionListLogOnServer)

            If TxtPathFileUpload.Text = "" Then
                ScriptManager.RegisterStartupScript(Me, _
                                                              Me.GetType(), _
                                                              "clientScript", _
                                                              "alert('กรุณาเลือกไฟล์ที่ต้องการอัพโหลด')", _
                                                              True)
            ElseIf ddlList.SelectedIndex = 0 Then
                ScriptManager.RegisterStartupScript(Me, _
                                                            Me.GetType(), _
                                                            "clientScript", _
                                                            "alert('กรุณาเลือกประเภท')", _
                                                            True)
                'ElseIf ddlList.SelectedValue = "99" And txtOther.Text.Trim = "" Then
                '    ScriptManager.RegisterStartupScript(Me, _
                '                                             Me.GetType(), _
                '                                             "clientScript", _
                '                                             "alert('กรุณาตั้งชื่อประเภทอื่นๆ')", _
                '                                             True)
            Else
                SanctionEntity = New SanctionEntities
                Dim SanctionList = (From tblSanctionList In SanctionEntity.MSANCTIONLIST _
                                    Where tblSanctionList.LISTTYPECODE = ddlList.SelectedValue _
                                    Select tblSanctionList.LISTTYPECODE, tblSanctionList.LISTTYPENAME, _
                                            tblSanctionList.FILENAME, tblSanctionList.BATCHJOB).ToList

                Dim strFileName As String = ""
                Dim strBatchJob As String = ""

                strFileName = SanctionList(0).FILENAME
                strBatchJob = SanctionList(0).BATCHJOB
                uploadFileToServer(strFileName)
                WriteBatFile(strBatchJob)

                If RunBatchFile() Then
                    Dim iCountTimer As Integer = 0

loop_TimeSleep:

                    If (iCountTimer < 7) Then
                        System.Threading.Thread.Sleep(5000)
                        If (FileExists(pathDriveOnServer & pathSanctionListLogOnServer & strFileName & ".log")) Then
                            Dim strMsg As String = readfile(pathDriveOnServer & pathSanctionListLogOnServer & strFileName & ".log")

                            WriteBatFile(readfile(System.Web.HttpContext.Current.Server.MapPath("~") & PathTextReadPathFuzzy))

                            If RunBatchFile() Then
                                System.Threading.Thread.Sleep(10000)
                                WriteBatFile("")
                            Else
                                System.Threading.Thread.Sleep(10000)
                                WriteBatFile("")
                            End If

                            'Dim lbl1 As New Label
                            'lbl1.Text = strMsg.Trim
                            'strMsg = lbl1.Text
                            'lbl1 = Nothing

                            'ScriptManager.RegisterStartupScript(Me, _
                            '                                             Me.GetType(), _
                            '                                             "clientScript", _
                            '                                             "alert('" & strMsg & "')", _
                            '                                             True)
                            Response.Write("<script>alert('" & strMsg.Trim & "');</script>")
                            statusUpload(2)
                        Else
                            iCountTimer += 1
                            GoTo loop_TimeSleep
                        End If

                        SaveLog(3)
                    Else
                        ScriptManager.RegisterStartupScript(Me, _
                                                            Me.GetType(), _
                                                            "clientScript", _
                                                            "alert('เกิดข้อผิดพลาด การอัพโหลดช้าเกินไปหรือไม่สำเร็จ')", _
                                                            True)

                    End If
                Else
                    ScriptManager.RegisterStartupScript(Me, _
                                                                      Me.GetType(), _
                                                                      "clientScript", _
                                                                      "alert('เกิดข้อผิดพลาด')", _
                                                                      True)
                End If

            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, _
                                                                       Me.GetType(), _
                                                                       "clientScript", _
                                                                      "alert('" + ex.Message + "')", _
                                                                       True)
        End Try

    End Sub


#Region "SetForm"

    Sub CreateControlMP()
        Dim page As Label = CType(Master.FindControl("lblPage"), Label)
        page.Text = "Sanction > นำเข้าข้อมูล"
    End Sub

#End Region


    Protected Sub ddlList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlList.SelectedIndexChanged
        'If ddlList.SelectedValue = "99" Then
        '    txtOther.Visible = True
        'Else
        '    txtOther.Visible = False
        'End If

        'If (ddlList.SelectedValue = "0") Then
        '    btnDelete.Attributes.Add("onclick", "return alert('กรุณาเลือกประเภท');")
        'Else
        btnDelete.Attributes.Add("onclick", "return confirm('ต้องการลบข้อมูลของ " + ddlList.SelectedValue + " List ใช่หรือไม่');")

        ' End If

    End Sub


#Region " Function "


    Private Sub uploadFileToServer(ByVal strFileName As String)
        Try
            Dim fn As String = ""
            Dim fnBackup As String = ""
            Dim strPathBatch As String = ""

            If (FileUpload1.Visible = True) Then
                TxtPathFileUpload.Text = FileUpload1.Value
            End If


            Dim strFileNameToSplit As String = TxtPathFileUpload.Text
            Dim arrString As String() = strFileNameToSplit.Split(".")
            fn = strFileName.Trim & "." & arrString(arrString.Length - 1)

            Dim savePath As String = Path.Combine(PathFileOnServer, fn)
            Dim backupPath As String = Path.Combine(PathFileBackupOnServer, fnBackup)
            fullUploadPath = savePath

            If (FileUpload1.Visible = True) Then
                FileUpload1.PostedFile.SaveAs(savePath)
            Else
                ' FileUpload1.PostedFile.SaveAs(pathSanctionListBackOnServer & fnBackup)
                ' File.Copy( sourceFileName, DistributionFileName )
                If File.Exists(savePath) = True Then
                    If File.Exists(backupPath) = True Then
                        DeleteFile(backupPath)
                        File.Copy(savePath, backupPath)
                    Else
                        File.Copy(savePath, backupPath)
                    End If

                End If
            End If

        Catch ex As Exception
            WriteError(ex, "uploadFileToServer", "frmImportData")
            Throw New Exception("เกิดข้อผิดพลาดในการอัพโหลดไฟล์")
        End Try

    End Sub

    Private Sub uploadFileToServer2(ByVal strFileName As String, ByVal uploadedFile As UploadedFile)
        Try
            Dim fn As String = ""
            Dim fnBackup As String = ""
            Dim strPathBatch As String = ""

            If (Not uploadedFile Is Nothing) Then
                TxtPathFileUpload.Text = uploadedFile.FileName
            End If


            Dim strFileNameToSplit As String = TxtPathFileUpload.Text
            Dim arrString As String() = strFileNameToSplit.Split(".")
            fn = strFileName.Trim & "." & arrString(arrString.Length - 1)

            Dim savePath As String = Path.Combine(PathFileOnServer, fn)
            Dim backupPath As String = Path.Combine(PathFileBackupOnServer, fnBackup)
            fullUploadPath = savePath

            If (Not uploadedFile Is Nothing) Then
                uploadedFile.SaveAs(savePath)
            Else
                ' FileUpload1.PostedFile.SaveAs(pathSanctionListBackOnServer & fnBackup)
                ' File.Copy( sourceFileName, DistributionFileName )
                If File.Exists(savePath) = True Then
                    If File.Exists(backupPath) = True Then
                        DeleteFile(backupPath)
                        File.Copy(savePath, backupPath)
                    Else
                        File.Copy(savePath, backupPath)
                    End If

                End If
            End If

        Catch ex As Exception
            WriteError(ex, "uploadFileToServer", "frmImportData")
            Throw New Exception("เกิดข้อผิดพลาดในการอัพโหลดไฟล์")
        End Try

    End Sub

    Private Function readXML(ByVal intSanctionType As Integer) As ISanctionListType
        Dim sanctionXML As ISanctionListType = Nothing
        Dim parseType As Type = Nothing
        Dim objStreamReader As New StreamReader(fullUploadPath)
        Try
            If intSanctionType = 0 Then ' EU Style
                parseType = GetType(RawEUXMLEntity)
                Dim rawEUXML As New RawEUXMLEntity()
                Dim x As New XmlSerializer(parseType)



                rawEUXML = x.Deserialize(objStreamReader)
                sactionListMapper.AddToEUTable(rawEUXML)
                sanctionXML = rawEUXML

            ElseIf intSanctionType = 1 Then ' OFAC Style
                parseType = GetType(RawOFACXMLEntity)

                Dim rawOFAC As New RawOFACXMLEntity()


                Dim x As New XmlSerializer(parseType)
                rawOFAC = x.Deserialize(objStreamReader)
                sanctionXML = rawOFAC
            ElseIf intSanctionType = 2 Then ' UN Style
                parseType = GetType(RawUNXMLEntity)

                Dim rawUN As New RawUNXMLEntity()
                Dim x As New XmlSerializer(parseType)
                rawUN = x.Deserialize(objStreamReader)
                sanctionXML = rawUN
            End If
        Catch ex As Exception

        Finally
            objStreamReader.Close()

        End Try



        ' Clear EU Data in DB before add

        'Dim sanctionLists As New ADOEntitySanctionList.SanctionListEntities

        'Dim d As Date = CDate("2012-02-23")
        '  Dim resDate As New Date()
        '  If DateTime.TryParseExact("2012-02-23", "yyyy-MM-dd", CultureInfo.InvariantCulture, _
        'DateTimeStyles.None, resDate) Then
        '      Console.WriteLine(resDate.ToString("yyyy/mm/dd"))
        '  Else
        '      Console.WriteLine("")
        '  End If
        'DateTime.Parse("2012-02-23").Date.ToString("YYYY-MM-DD")
        'Dim rawOF As New RawOFACXMLEntity
        'Dim publishInfo As New RawOFACXMLEntity.PublishDate
        'publishInfo.publish_date = "publish date"
        'publishInfo.record_count = 1

        'Dim listSDN As New List(Of RawOFACXMLEntity.SDNEntity)
        'Dim snd1 As New RawOFACXMLEntity.SDNEntity
        'snd1.firstName = "XX"
        'listSDN.Add(snd1)
        'Dim programlist As New RawOFACXMLEntity.ProgramList
        'Dim pl As New List(Of String)
        'pl.Add("CUBA")
        'pl.Add("CUBA2")
        'programlist.program = pl
        'snd1.programListEntity = programlist
        'rawOF.SDNListProperty = listSDN

        'Dim rawUN As New RawUNXMLEntity

        'Dim ind1 As New RawUNXMLEntity.Individual
        'Dim listInd As New List(Of RawUNXMLEntity.Individual.IndividualDetail)
        'Dim indDetail As RawUNXMLEntity.Individual.IndividualDetail
        'ind1.IndividualListProperty = listInd
        'For counter As Integer = 0 To 5
        '    indDetail = New RawUNXMLEntity.Individual.IndividualDetail
        '    indDetail.data_id = counter
        '    indDetail.version_number = 100 + counter
        '    listInd.Add(indDetail)
        'Next

        'Dim ent1 As New RawUNXMLEntity.Entities
        'Dim listEnt As New List(Of RawUNXMLEntity.Entities.EntityDetail)
        'Dim entDetail As RawUNXMLEntity.Entities.EntityDetail
        'ent1.EntitieDetails = listEnt
        'For counter As Integer = 0 To 5
        '    entDetail = New RawUNXMLEntity.Entities.EntityDetail
        '    entDetail.data_id = counter
        '    entDetail.version_number = 100 + counter
        '    listEnt.Add(entDetail)
        'Next

        'rawUN.entitiesInstance = ent1
        'rawUN.individualsInstance = ind1


        'Dim x2 As New XmlSerializer(GetType(RawUNXMLEntity))
        'Dim objStreamWriter As New StreamWriter(PathFileOnServer + "/test3.xml")

        'x2.Serialize(objStreamWriter, rawUN)
        'objStreamWriter.Close()

        'Console.WriteLine(rawEUXML.euDate)

        ' Check Sanction list type and choose matching type
        Return sanctionXML

    End Function

    Private Function unzipFile() As String
        'Declare the shell object
        Dim shObj As Object = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"))
        Dim outputFolder As String = fullUploadPath
        Dim inputFolder As String = fullUploadPath

        outputFolder = outputFolder.Split(".")(0)
        'Create directory in which you will unzip your items.
        IO.Directory.CreateDirectory(outputFolder)

        'Declare the folder where the items will be extracted.
        Dim output As Object = shObj.NameSpace((outputFolder))

        'Declare the input zip file.
        Dim input As Object = shObj.NameSpace((inputFolder))

        'Extract the items from the zip file.
        output.CopyHere((input.Items), 4)

        Return outputFolder
    End Function

    Private Function ReadCSV(ByVal pathFile As String, ByVal fileName As String) As DataTable
        'Dim excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=""Excel 12.0;"""
        Dim excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & pathFile & ";Extended Properties=""Text;HDR=YES;FMT=Delimited;CharacterSet=65001"";"
        'Dim excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & fileName & ";Extended Properties=""text;HDR=No;FMT=Delimited"";"
        'Dim excelConnectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source = " & pathFile & "; Extended Properties = ""Text;HDR=YES;FMT=Delimited;CharacterSet=65001"";"
        'Dim excelConnectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source = " & pathFile & "; Extended Properties = ""Text;HDR=YES;FMT=Delimited"";"
        Dim dt = New DataTable()
        dt.TableName = fileName.Split(".")(0)
        Try
            Using con As New OleDbConnection(excelConnectionString)
                con.Open()

                Dim sheetName = con.GetSchema("Tables").Rows(0)("TABLE_NAME")
                Dim cmd = New OleDbDataAdapter("select * from [" + fileName + "]", con)
                cmd.Fill(dt)

                con.Close()
            End Using
        Catch ex As Exception

        End Try
        Return dt
    End Function
    Private Function convertFileName2AMLOTableName(ByVal strFileName As String) As String
        Dim resTblName As String = ""
        If strFileName.ToLower.Contains("address") Then
            resTblName = "address"
        ElseIf strFileName.ToLower.Contains("classification") Then
            resTblName = "classification"
        ElseIf strFileName.ToLower.Contains("criminal") Then
            resTblName = "criminal"
        ElseIf strFileName.ToLower.Contains("description") Then
            resTblName = "description"
        ElseIf strFileName.ToLower.Contains("education") Then
            resTblName = "education"
        ElseIf strFileName.ToLower.Contains("false") Then
            resTblName = "falsepositive"
        ElseIf strFileName.ToLower.Contains("idnumber") Then
            resTblName = "idnumber"
        ElseIf strFileName.ToLower.Contains("image") Then
            resTblName = "image"
        ElseIf strFileName.ToLower.Contains("master") Then
            resTblName = "master"
        ElseIf strFileName.ToLower.Contains("name") Then
            resTblName = "name"
        ElseIf strFileName.ToLower.Contains("birth") Then
            resTblName = "birth"
        ElseIf strFileName.ToLower.Contains("relationship") Then
            resTblName = "relationship"
        ElseIf strFileName.ToLower.Contains("resident") Then
            resTblName = "resident"
        ElseIf strFileName.ToLower.Contains("role") Then
            resTblName = "role"
        ElseIf strFileName.ToLower.Contains("sanction") Then
            resTblName = "sanction"
        ElseIf strFileName.ToLower.Contains("source") Then
            resTblName = "source"
        ElseIf strFileName.ToLower.Contains("str") Then
            resTblName = "str"
        ElseIf strFileName.ToLower.Contains("vessel") Then
            resTblName = "vessel"
        End If

        Return resTblName
    End Function

#Region "Validate Sacntion"
    Private Function validateSanctionList(ByVal sanctionObj As ISanctionListType, ByVal dsSanction As DataSet) As Integer

        Dim intRes = 0
        ' Use intRes for tell about result and failure reason
        ' 0 = success
        ' 1 = wrong format
        ' 2 = duplicate file (only CDD zip file)
        ' 3 = empty file (correct format)

        If sanctionObj Is Nothing AndAlso dsSanction Is Nothing Then
            intRes = 1

            Return intRes
            ' Check TimeStam of this file ,If it contain in DB it same file
        End If

        If Not sanctionObj Is Nothing Then
            Dim value = sanctionObj.GetTypes
            Select Case value
                Case sanctionListType.UN
                    Dim unList = DirectCast(sanctionObj, RawUNXMLEntity)
                    If Not unList Is Nothing Then
                        If Not unList.individualsInstance.IndividualListProperty Is Nothing Then
                            Dim listEnt = unList.individualsInstance.IndividualListProperty
                            If listEnt.Count > 0 Then
                                Dim unEntID As Integer = -1

                                If listEnt(0).data_id > 0 Then
                                    unEntID = listEnt(0).data_id
                                End If
                                Dim unEntName = listEnt(0).first_name
                                If unEntID > 0 And Not String.IsNullOrEmpty(unEntName) Then
                                    intRes = 0

                                Else
                                    intRes = 3

                                End If
                            Else
                                intRes = 3

                            End If
                        Else
                            intRes = 1

                        End If
                    Else
                        intRes = 1

                    End If
                   
                Case sanctionListType.OFAC
                    Dim ofacList = DirectCast(sanctionObj, RawOFACXMLEntity)
                    If Not ofacList Is Nothing Then
                        If Not ofacList.SDNListProperty Is Nothing Then
                            Dim listEnt = ofacList.SDNListProperty
                            If listEnt.Count > 0 Then
                                Dim unEntID As Integer = -1
                                If listEnt(0).uid > 0 Then
                                    unEntID = listEnt(0).uid
                                End If
                                If unEntID > 0 Then
                                    intRes = 0

                                Else
                                    intRes = 3

                                End If
                            Else
                                intRes = 3

                            End If
                        Else
                            intRes = 1

                        End If
                    Else
                        intRes = 1

                    End If


                Case sanctionListType.EU
                    Dim euList = DirectCast(sanctionObj, RawEUXMLEntity)
                    If Not euList Is Nothing Then
                        Dim listEnt = euList.listEntity
                        If Not listEnt Is Nothing Then
                            If listEnt.Count > 0 Then
                                Dim euEntID As Integer = -1
                                If listEnt(0)._id > 0 Then
                                    euEntID = listEnt(0)._id
                                End If

                                Dim listName = listEnt(0).EUNameProperty
                                If Not listName Is Nothing AndAlso listName.Count > 0 Then
                                    Dim allName = listName(0)._firstName + listName(0)._lastName + listName(0)._middleName + listName(0)._wholeName
                                    If euEntID > 0 AndAlso Not String.IsNullOrEmpty(allName) Then
                                        intRes = 0

                                    Else
                                        intRes = 3

                                    End If
                                Else
                                    intRes = 3

                                End If
                            Else
                                intRes = 1
                            End If
                        Else
                            intRes = 1

                        End If
                    Else
                        intRes = 1

                    End If


            End Select
        Else ' Valilate 18 File
            Dim tblMaster = dsSanction.Tables("master")
            Dim tblName = dsSanction.Tables("name")
            If Not tblMaster Is Nothing AndAlso Not tblName Is Nothing Then
                If tblMaster.Rows.Count > 0 AndAlso tblName.Rows.Count > 0 Then
                    Dim entID = ""
                    Dim allName = ""
                    Dim infoSource = ""
                    Try
                        entID = tblMaster.Rows(0)(0).ToString
                        infoSource = tblMaster.Rows(0)(1).ToString
                        allName = tblName.Rows(0)(3).ToString + tblName.Rows(0)(4).ToString + tblName.Rows(0)(5).ToString + tblName.Rows(0)(7).ToString + tblName.Rows(0)(9).ToString + tblName.Rows(0)(10).ToString
                    Catch ex As Exception
                        intRes = 1
                    End Try

                    If Not String.IsNullOrEmpty(entID) AndAlso Not String.IsNullOrEmpty(allName) Then
                        Dim sanctionAll As New ADOEntitySanctionList.SanctionListEntities

                        Dim currentFileSTTM = tblMaster.Rows(0)(26) '06/08/2013 18:23
                        If Not String.IsNullOrEmpty(currentFileSTTM) Then
                            Dim resDate As New Date

                            currentFileSTTM = tblMaster.Rows(0)(26).ToString().Split(" ")
                            DateTime.TryParseExact(currentFileSTTM(0), _
                               {"dd/MM/yyyy", "yyyyMMdd"}, CultureInfo.InvariantCulture, _
                               DateTimeStyles.None, resDate)

                            Dim sameTimeStamp = (From m In sanctionAll.AMLO_NEW_MASTER_TEMP Where m.INFO_SOURCE.Equals(infoSource) And m.STAMP_DTTM = resDate Select m.STAMP_DTTM)
                            If Not sameTimeStamp.Any Then
                                intRes = 0

                            Else
                                intRes = 2

                            End If
                        Else
                            intRes = 3
                        End If


                    Else
                        intRes = 3

                    End If
                End If
            Else
                intRes = 1

            End If
        End If

        Return intRes
    End Function
#End Region

    Private Sub btnCopyHere_Click()
        'Dim objShell As Shell
        'Dim objFolder As Folder

        'objShell = New Shell
        'objFolder = objShell.NameSpace("C:\WINDOWS")

        'If (Not objFolder Is Nothing) Then
        '    objFolder.CopyHere("C:\AUTOEXEC.BAT")
        'End If

        'objFolder = Nothing
        'objShell = Nothing


    End Sub

    'Private Sub uploadFileToServer(ByVal strFileName As String)
    '    Try
    '        Dim fn As String = ""
    '        Dim fnBackup As String = ""
    '        Dim strPathBatch As String = ""

    '        If (FileUpload1.Visible = True) Then
    '            TxtPathFileUpload.Text = FileUpload1.Value
    '        End If


    '        Dim strFileNameToSplit As String = TxtPathFileUpload.Text
    '        Dim arrString As String() = strFileNameToSplit.Split(".")
    '        fn = strFileName.Trim & "." & arrString(arrString.Length - 1)
    '        fnBackup = strFileName.Trim & "_" & stringDate(txtDate.Text) & "." & arrString(arrString.Length - 1)

    '        If (FileUpload1.Visible = True) Then
    '            FileUpload1.PostedFile.SaveAs(pathDriveOnServer & pathSanctionListOnServer & fn)
    '        Else
    '            ' FileUpload1.PostedFile.SaveAs(pathSanctionListBackOnServer & fnBackup)
    '            ' File.Copy( sourceFileName, DistributionFileName )
    '            If File.Exists(pathDriveOnServer & pathSanctionListOnServer & fn) = True Then
    '                If File.Exists(pathDriveOnServer & pathSanctionListBackOnServer & fnBackup) = True Then
    '                    DeleteFile(pathDriveOnServer & pathSanctionListBackOnServer & fnBackup)
    '                    File.Copy(pathDriveOnServer & pathSanctionListOnServer & fn, pathDriveOnServer & pathSanctionListBackOnServer & fnBackup)
    '                Else
    '                    File.Copy(pathDriveOnServer & pathSanctionListOnServer & fn, pathDriveOnServer & pathSanctionListBackOnServer & fnBackup)
    '                End If

    '            End If
    '        End If

    '    Catch ex As Exception
    '        WriteError(ex, "uploadFileToServer", "frmImportData")
    '        Throw New Exception("เกิดข้อผิดพลาดในการอัพโหลดไฟล์")
    '    End Try

    'End Sub



    Private Sub LoadSanctionList()
        Try
            Dim AddItem As ListItem = Nothing

            SanctionEntity = New SanctionEntities

            Dim SanctionList = (From tblSanctionList In SanctionEntity.MSANCTIONLIST Select tblSanctionList.LISTTYPECODE, tblSanctionList.LISTTYPENAME).ToList
            AddItem = New ListItem("** กรุณาเลือกประเภทความเสี่ยง **", 0)

            ddlList.Items.Clear()
            ddlList.DataSource = SanctionList
            ddlList.DataTextField = "LISTTYPENAME"
            ddlList.DataValueField = "LISTTYPECODE"
            ddlList.DataBind()

            ddlList.Items.Insert(0, AddItem)

            SanctionEntity = Nothing
        Catch ex As Exception
            WriteError(ex, "LoadSanctionList", "frmImportData")
        End Try

    End Sub

    Private Sub loadDataToDropDown()
        Try
            Dim clsDropDown As New clsMasterDropDown
            clsDropDown.setSource(ddlList)
            clsDropDown = Nothing
        Catch ex As Exception
            WriteError(ex, "loadDataToDropDown", "SanctionHistory")
            Throw ex
        End Try
    End Sub

    Private Function stringDate(ByVal strDate As String) As String
        Try
            Dim d() As String = strDate.Split("/")
            strDate = d(2) + d(1) + d(0)
        Catch ex As Exception
            WriteError(ex, "stringDate", "frmImportData")
        End Try
        Return strDate
    End Function

    Private Function RunBatchFile() As Boolean
        Dim blnComple As Boolean = False
        Dim testtext As String = ""
        Try
            Dim psi As New System.Diagnostics.ProcessStartInfo("cmd.exe")
            psi.UseShellExecute = False
            psi.RedirectStandardInput = True
            psi.RedirectStandardOutput = True
            psi.RedirectStandardError = True
            psi.WorkingDirectory = pathDriveOnServer & "\\Sanction_List_Batch\\"
            'DECLARE PROCESS

            Dim proc As System.Diagnostics.Process
            proc = System.Diagnostics.Process.Start(psi)
            'PATH OPENED AS TEXT BY STREAM READER

            ''INPUT
            Dim sin As System.IO.StreamWriter
            sin = proc.StandardInput
            ''COMMAND TO CMD
            sin.WriteLine(readfile(pathDriveOnServer & PathFileFloderBatch))
            System.Threading.Thread.Sleep(5000)
            sin.WriteLine("EXIT")
            proc.Close()

            sin.Close()

            blnComple = True
        Catch ex As Exception

            WriteError(ex, "RunBatchFile", "frmImportData")
            Throw New Exception("เกิดข้อผิดพลาด RunBatchFile ")
            blnComple = False
        End Try
        Return blnComple
    End Function

    Private Function FileExists(ByVal FileFullPath As String) As Boolean
        Try
            Dim f As New IO.FileInfo(FileFullPath)
            Return f.Exists
        Catch ex As Exception
            WriteError(ex, "FileExists", "frmImportData")

            Throw New Exception("เกิดข้อผิดพลาด FileExists ")
        End Try
    End Function

    Private Function DeleteFileInDirectory(ByVal targetDirectory As String) As Boolean
        Dim blnSuccess As Boolean = False
        Dim strTest As String = ""

        Try
            strTest = 1
            Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
            strTest = 2
            ' Process the list of files found in the directory.
            Dim fileName As String

            For Each fileName In fileEntries
                strTest = 3
                File.Delete(fileName)
            Next fileName
            strTest = 4
            System.IO.Directory.Delete(targetDirectory, True)
            strTest = 5
            blnSuccess = True

        Catch ex As Exception
            WriteError(ex, "DeleteFileInDirectory", "frmImportData")
            Throw New Exception("เกิดข้อผิดพลาด DeleteFileInDirectory " & strTest)
        End Try
        Return blnSuccess
    End Function

    Private Function DeleteFile(ByVal FileName As String) As Boolean
        Dim blnSuccess As Boolean = False
        Try
            File.Delete(FileName)
            blnSuccess = True
        Catch ex As Exception
            WriteError(ex, "DeleteFile", "frmImportData")
            Throw New Exception("เกิดข้อผิดพลาด DeleteFile ")
        End Try
        Return blnSuccess
    End Function

    Private Function readfile(ByVal FileFullPath As String) As String
        Dim strMsg As String = ""
        Try
            Dim srd As StreamReader = New System.IO.StreamReader(FileFullPath, System.Text.Encoding.UTF8)
            strMsg = srd.ReadToEnd()
            srd.Close()
        Catch ex As Exception
            WriteError(ex, "readfile", "frmImportData")
            Throw New Exception("เกิดข้อผิดพลาด readfile ")
        End Try
        Return strMsg
    End Function


    Public Sub statusUpload(ByVal status As Integer)
        If (status = 0 Or status = 2) Then
            ddlList.Enabled = True
            ddlList.SelectedIndex = 0
            FileUpload1.Visible = True
            TxtPathFileUpload.Visible = False
            TxtPathFileUpload.Text = ""
            hdfUpload.Value = ""
            hdfCountRow.Value = ""
            btnTestUpload.Enabled = True
            btnUpload.Enabled = False
            lblCountRow.Text = ""
            grdAmlList.DataSource = Nothing
            grdAmlList.DataBind()
        ElseIf (status = 1) Then
            FileUpload1.Visible = False
            TxtPathFileUpload.Visible = True
            btnTestUpload.Enabled = False
            ddlList.Enabled = False
        End If

    End Sub



#End Region



    Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        'ddlList.SelectedIndex = 0
        'FileUpload1.Visible = True
        'TxtPathFileUpload.Visible = False
        'TxtPathFileUpload.Text = ""
        'hdfUpload.Value = ""
        'hdfCountRow.Value = ""
        'btnTestUpload.Enabled = True
        'btnUpload.Enabled = False
        'lblCountRow.Text = ""
        statusUpload(0)
    End Sub

    Protected Sub m(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim cls As clsDatabase = New clsDatabase
        Dim col As Collection = New Collection
        Dim objClsVariable As clsVariable = New clsVariable
        Try
            If (ddlList.SelectedIndex = 0) Then
                ScriptManager.RegisterStartupScript(Me, _
                                                    Me.GetType(), _
                                                    "clientScript", _
                                                    "alert('กรุณาเลือกประเภท')", _
                                                    True)

            Else

                objClsVariable.nameColumn = "datasource"
                objClsVariable.valueColumn = ddlList.SelectedValue

                col.Add(objClsVariable)


                cls.TransStart()
                Dim strSql As String = ""
                strSql = "delete from KYCADMIN.AMLLIST_THAI where datasource = :datasource "
                cls.TransExecute(strSql, col)
                strSql = "delete from KYCADMIN.AMLLIST_OTHER where datasource = :datasource "
                cls.TransExecute(strSql, col)

                strSql = "delete from KYCADMIN.AMLLIST_THAI_MC75 where datasource = :datasource "
                cls.TransExecute(strSql, col)

                strSql = "delete from KYCADMIN.AMLLIST_OTHER_MC65 where datasource = :datasource "
                cls.TransExecute(strSql, col)

                Dim mStrimportID = (From tblImport In SanctionListNewEntity.AMLO_NEW_IMPORT_TEMP Where tblImport.FILE_TYPE.Equals(ddlList.SelectedItem.Text) Select tblImport.IMPORTID).Max

                strSql = "Update  KYCADMIN.amlo_new_master_temp set existing_status=1 where IMPORTID = " + mStrimportID.ToString + " and existing_status = 0 "
                cls.TransExecute(strSql, col)

                cls.TransCommit()
            End If

            SaveLog(5)
        Catch ex As Exception
            cls.TransRollBack()
            WriteError(ex, "btnDelete_Click", "frmImportData")

            ScriptManager.RegisterStartupScript(Me, _
                                                                   Me.GetType(), _
                                                                   "clientScript", _
                                                                  "alert('" + "เกิดข้อผิดพลาด" + "')", _
                                                                   True)

        End Try




    End Sub

    Private Sub WriteBatFile(ByVal strNameFileBat As String)
        Try

            Dim strText As String = ""
            Dim StreamReader1 As System.IO.StreamReader = System.IO.File.OpenText(pathDriveOnServer & PathFileFloderBatchTest)
            strText = StreamReader1.ReadToEnd()
            StreamReader1.Close()

            Dim intText As Integer = 0
            intText = strText.Length

            'ScriptManager.RegisterStartupScript(Me, _
            '                                                     Me.GetType(), _
            '                                                     "clientScript", _
            '                                                    "alert('" + strText + "')", _
            '                                                     True)

            Dim strTextReplace As String = strText.Replace(strText.Substring(strText.IndexOf("/tn"), strText.Length - strText.IndexOf("/tn")), "/tn " & strNameFileBat)



            Dim StreamWriter1 As System.IO.StreamWriter = New System.IO.StreamWriter(pathDriveOnServer & PathFileFloderBatchTest)
            StreamWriter1.WriteLine(strTextReplace)
            StreamWriter1.Close()

        Catch ex As Exception
            WriteError(ex, "WriteBatFile", "frmImportData")
            Throw New Exception("เกิดข้อผิดพลาดการเขียนไฟล์ " & ex.Message)

        End Try


    End Sub
    'Private Function ReadFile() As String
    '    Dim strReadText As String = ""
    '    Try
    '        Dim strm As System.IO.StreamReader
    '        strm = System.IO.File.OpenText(PathFileFloderBatch)
    '        strReadText = strm.ReadLine()
    '    Catch ex As Exception

    '    End Try

    '    Return ""
    'End Function

    Private Sub SaveLog(ByVal index As Integer)
        Try
            Dim program As String = "M73"
            Dim programName As String = " Sanction > นำเข้าข้อมูล"

            Dim desc As String = ""

            If index = 3 Then
                desc = "บันทึก" + programName + " (นำเข้าข้อมูล " + ddlList.SelectedItem.Text + ")"
            ElseIf index = 5 Then
                desc = "ลบ" + programName + " (นำเข้าข้อมูล " + ddlList.SelectedItem.Text + ")"
            End If

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction("", clsSessionMenuRight.getUserName, index, desc, program)


            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub


    Public Sub New()

    End Sub


    Protected Sub grdAmlList_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdAmlList.PageIndexChanging
        grdAmlList.PageIndex = e.NewPageIndex
        grdAmlList.DataSource = Session("amllist_test")
        grdAmlList.DataBind()
    End Sub


    Protected Sub btnTestScript_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnTestScript.Click

        Dim objCallFuzzyEN As New procDQEN.ProcDQsvrsvc_en
        Dim objPrmFuzzyName As New procDQEN.Parameters

        'Dim objCallDataEN As New wsvSearchEn.ProcDQsvrsvc_en
        'Dim objPrmNameEN As New wsvSearchEn.Parameters
        'With objPrmNameEN
        '    .firstName = "Lojer"
        '    .middleName = ""
        '    .lastName = ""
        'End With

        With objPrmFuzzyName
            .firstName = "Lojer"
            .middleName = ""
            .lastName = ""
        End With

        Dim res = objCallFuzzyEN.procDQsvrsvc_en(objPrmFuzzyName)
        Dim doc As XmlDocument = New XmlDocument

        doc.LoadXml(res)
        Dim dsService As New DataSet
        dsService.ReadXml(New XmlNodeReader(doc))
    
        Console.Write("")

        'Dim result = Windows.Forms.MessageBox.Show(New Windows.Forms.Form() With {.TopMost = True _
        '}, "I'm on top!", "title", Windows.Forms.MessageBoxButtons.YesNo)
        'If result = Windows.Forms.DialogResult.Yes Then
        '    Console.Write("A")
        'ElseIf result = Windows.Forms.DialogResult.No Then
        '    Console.Write("B")
        'End If

        'Dim confirmValue As String = Request.Form("confirm_value")
        'If confirmValue = "Yes" Then

        'ClientScript.RegisterStartupScript(Me.[GetType](), "confirm", "Confirm()", True)
        '  hdfmsg.Value = "Message on own click"
        '  ScriptManager.RegisterClientScriptBlock(Me, Me.[GetType](), "script",
        '"Confirm();", True)
        '  Console.Write("")
        'Else
        'ClientScript.RegisterStartupScript(Me.[GetType](), "alert", "alert('You clicked NO!')", True)
        'End If
    End Sub

    Protected Sub hdfButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles hdfButton.Click

        fullUploadPath = hdfmsg.Value
        strFileTypeCode = hdfSanctionCode.Value
        strListFileTypeCode = hdfSanctionTypeCode.Value
        strFileType = hdfSanctionFileType.Value


        ' Check Extension
        Dim fullPathSplit As String() = fullUploadPath.Split(".")
        If fullPathSplit.Length > 0 Then
            If Not (fullPathSplit(fullPathSplit.Length - 1).ToLower.Equals("xml") Or
                fullPathSplit(fullPathSplit.Length - 1).ToLower.Equals("zip") Or
                fullPathSplit(fullPathSplit.Length - 1).ToLower.Equals("csv")) Then

                DeleteFile(fullUploadPath)
                btnCancel.Enabled = True
                ScriptManager.RegisterStartupScript(Me, _
                                                      Me.GetType(), _
                                                      "clientScript", _
                                                      "alert('เกิดข้อผิดพลาด นามสกุลของเอกสารที่นำเข้าไม่ถูกค้อง')", _
                                                      True)
                Return
            End If
        Else
            ScriptManager.RegisterStartupScript(Me, _
                                                      Me.GetType(), _
                                                      "clientScript", _
                                                      "alert('เกิดข้อผิดพลาด นามสกุลของเอกสารที่นำเข้าไม่ถูกค้อง')", _
                                                      True)
            Return
        End If


        ' If XML file need to parsing to obj before push to raw DB
        Dim selectedIndex As Integer = ddlList.SelectedIndex
        Dim sanctionListObj As ISanctionListType = Nothing
        Dim ds As DataSet = Nothing
        Dim resValidate = 0
        Dim intSanctionXMLStyle As Integer = -1
        'If (selectedIndex > 2 And selectedIndex < 6) Then
        If (strFileTypeCode.Equals("2")) Then

            If strListFileTypeCode.ToLower.Contains("eu") Then
                intSanctionXMLStyle = 0
            ElseIf strListFileTypeCode.ToLower.Contains("ofac") Then
                intSanctionXMLStyle = 1
            ElseIf strListFileTypeCode.ToLower.Contains("un") Then
                intSanctionXMLStyle = 2
            End If
            ' Read XML and put to original DB
            sanctionListObj = readXML(intSanctionXMLStyle)
            DeleteFile(fullUploadPath)
        ElseIf strFileTypeCode.Equals("3") Then
            Console.Write("path " & fullUploadPath)
            Dim rawFileName = fullUploadPath.Split("\")
            Dim strRawFileName = rawFileName(rawFileName.Length - 1)
            Dim strRawFilePath = fullUploadPath.Substring(0, fullUploadPath.IndexOf(strRawFileName) - 1)
            ReadCSV(strRawFilePath, strRawFileName)
            Console.Write("")
        Else
            ' This case mean : Single Excel or ZIP file that need to parsing before push to Original DB
            Dim pathUnzip = unzipFile()


            Dim file = My.Computer.FileSystem.GetFiles(pathUnzip)
            Dim counter = file.Count
            ds = New DataSet(strFileType)
            For i As Integer = 0 To counter - 1
                If Not file Is Nothing Then
                    Dim rawFileName As String = Path.GetFileName(file(i))
                    Try
                        ' Convert to UTF-8
                        Dim createText = IO.File.ReadAllLines(file(i), Encoding.UTF8)
                        IO.File.WriteAllLines(file(i), createText, Encoding.UTF8)
                    Catch ex As Exception

                    End Try
                    Dim dt = ReadCSV(pathUnzip, rawFileName)
                    dt.TableName = convertFileName2AMLOTableName(rawFileName)
                    ds.Tables.Add(dt)
                End If
            Next
            DeleteFile(fullUploadPath)
            DeleteFileInDirectory(pathUnzip)
        End If

        Dim clsDate As New clsDateFormat


        resValidate = validateSanctionList(sanctionListObj, ds)
        Dim currUploadDateTime = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss", New CultureInfo("en-GB"))

        If resValidate = 0 Then
            ' Formatting data from original DB and put to Temp DB
            If intSanctionXMLStyle = 0 Then ' EU XML File
                infoSource = sactionListMapper.addEU2TempDB(sanctionListObj, strFileName, strListFileTypeCode, currUploadDateTime, clsSessionMenuRight.getUserName)
            ElseIf intSanctionXMLStyle = 1 Then ' OFAC XML File
                infoSource = sactionListMapper.addOFACTable(sanctionListObj, strFileName, strListFileTypeCode, currUploadDateTime, clsSessionMenuRight.getUserName)
            ElseIf intSanctionXMLStyle = 2 Then ' UN XML File
                infoSource = sactionListMapper.addToUNTable(sanctionListObj, strFileName, strListFileTypeCode, currUploadDateTime, clsSessionMenuRight.getUserName)
            Else
                If Not ds Is Nothing Then
                    infoSource = sactionListMapper.addToAMLAndTemp(ds, strFileName, strListFileTypeCode, currUploadDateTime, clsSessionMenuRight.getUserName)
                    'Console.Write("")
                End If
            End If

            ' Skip write batch file
            'WriteBatFile(strBatchTestJob)

            'If RunBatchFile() Then
            If True Then ' Skip run script file
                Dim iCountTimer As Integer = 0

loop_TimeSleep:

                If (iCountTimer < 7) Then
                    System.Threading.Thread.Sleep(5000)
                    'If (FileExists(pathDriveOnServer & pathSanctionListLogOnServer & strFileName & NameFileTest & ".log")) Then
                    If (True) Then ' Skip check log file
                        Dim strMsg As String = ""
                        Try
                            strMsg = readfile(pathDriveOnServer & pathSanctionListLogOnServer & strFileName & NameFileTest & ".log")
                        Catch ex As Exception
                        End Try

                        '----------------------------
                        'ทำการ count row แล้วเอาค่าไปไว้้ที่ hdfCountRow.Value
                        'แล้วเอา hdfCountRow.Value ไปใส่ที่ lblCountRow.text
                        '----------------------------
                        Dim clsDatabase As New clsDatabase
                        Dim intCountRow As Integer = 0
                        Dim ds_test As New DataSet

                        '=== Old Version
                        'Dim sqlShow As String = " select uniqueid,firstname,middlename,lastname,fullname,datasource,risklevel from " & System.Configuration.ConfigurationSettings.AppSettings("TableAMLLIST_TEST") & "  where rownum<=10 "
                        'Dim sqlCount As String = " select count(*) from " & System.Configuration.ConfigurationSettings.AppSettings("TableAMLLIST_TEST")
                        '=== New Version
                        Dim SanctionListAll As New ADOEntitySanctionList.SanctionListEntities
                        Dim maxImportID = (From tblImport In SanctionListAll.AMLO_NEW_IMPORT_TEMP Select tblImport.IMPORTID).Max
                        Dim sqlShow = ""
                        If maxImportID > 0 Then
                            'sqlShow = " select m.entity_id,m.info_source, i.id_value ,n.firstname_e , n.middle_name_e,n.surname_e,n.single_string_name," +
                            '    " n.first_name,n.middle_name,n.surname" +
                            '    " from KYCADMIN.amlo_new_master_temp m" +
                            '    " left join KYCADMIN.amlo_new_idnumber_temp i on  m.entity_id = i.entity_id" +
                            '    " left join KYCADMIN.amlo_new_name_temp n on  m.entity_id = n.entity_id" +
                            '    " where m.importid = '" + maxImportID.ToString + "'"

                            sqlShow = " select m.entity_id as entID ,m.info_source as DataSource, i.id_value as uniqueid,n.firstname_e as FirstNameEng , n.middle_name_e as MiddleNameEng,n.surname_e as LastNameEng,n.ENTITY_NAME_E as EntityNameEng,n.ENTITY_NAME as EntityName," +
                                " n.FIRST_NAME as FirstName , n.MIDDLE_NAME as MiddleName,n.SURNAME as LastName" +
                                " from KYCADMIN.amlo_new_master_temp m" +
                                " left join KYCADMIN.amlo_new_idnumber_temp i on  m.entity_id = i.entity_id" +
                                " left join KYCADMIN.amlo_new_name_temp n on  m.entity_id = n.entity_id" +
                                " where m.importid = '" + maxImportID.ToString + "' "

                            sqlShow = "select * from (" + sqlShow + ") where rownum <= 50"
                        End If
                        'Dim sqlCount As String = " select count(*) from " & System.Configuration.ConfigurationSettings.AppSettings("TableAMLLIST_TEST")
                        Dim sqlCount As String = " select count(*) from KYCADMIN.amlo_new_master_temp m where m.info_source = '" & infoSource & "'"

                        ' intCountRow = ds_test.Tables("amllist_test").Rows.Count
                        Try
                            intCountRow = clsDatabase.QueryExecuteScalar(sqlCount)
                        Catch ex As Exception
                            intCountRow = 0
                        End Try

                        ds_test = clsDatabase.QueryDataSet(sqlShow, "amllist_test")
                        Session("amllist_test") = ds_test
                        'grdAmlList.DataSource = ds_test.Tables("amllist_test")
                        'grdAmlList.DataBind()

                        If (intCountRow = 0) Then
                            hdfCountRow.Value = ""
                            btnUpload.Enabled = False
                        Else
                            If intCountRow > 1 Then
                                hdfCountRow.Value = intCountRow & " Records"
                            Else
                                hdfCountRow.Value = intCountRow & " Record"
                            End If
                            btnUpload.Enabled = True
                        End If


                        TxtPathFileUpload.Text = hdfUpload.Value
                        lblCountRow.Text = hdfCountRow.Value
                        'FileUpload1.Visible = False
                        'TxtPathFileUpload.Visible = True
                        'btnTestUpload.Enabled = False
                        'Response.Write("<script>alert('" & "21MAR11:15:47:17 Successful" & "');</script>")
                        statusUpload(1)
                        btnCancel.Enabled = True
                        'Dim lbl1 As New Label
                        'lbl1.Text = strMsg.Trim
                        'strMsg = lbl1.Text
                        'lbl1 = Nothing

                        'ScriptManager.RegisterStartupScript(Me, _
                        '                                             Me.GetType(), _
                        '                                             "clientScript", _
                        '                                             "alert('" & strMsg & "')", _
                        '                                             True)
                        'Response.Write("<script>alert('" & strMsg.Trim & "');</script>")
                        ScriptManager.RegisterStartupScript(Me, _
                                                               Me.GetType(), _
                                                               "clientScript", _
                                                               "alert('Success')", _
                                                               True)

                        'ScriptManager.RegisterStartupScript(Me, _
                        '                                       Me.GetType(), _
                        '                                       "clientScript", _
                        '                                       "alert('" & strMsg.Replace(":", "-").Replace(" ", "") & "')", _
                        '                                       True)
                    Else
                        iCountTimer += 1
                        GoTo loop_TimeSleep
                    End If
                Else
                    btnCancel.Enabled = True
                    ScriptManager.RegisterStartupScript(Me, _
                                                        Me.GetType(), _
                                                        "clientScript", _
                                                        "alert('เกิดข้อผิดพลาด การอัพโหลดช้าเกินไปหรือไม่สำเร็จ')", _
                                                        True)
                End If
            End If

        Else ' This case when invalid sanction list
            Dim reasonFail As String = ""

            Select Case resValidate
                Case 1
                    reasonFail = "เกิดข้อผิดพลาด เอกสารที่นำเข้ามีรูปแบบไม่ตรงกับชนิดเอกสารที่เลือก"
                Case 2
                    reasonFail = "เกิดข้อผิดพลาด เอกสารนำเข้าเป็นเอกสารซ้ำ"
                Case 3
                    reasonFail = "เกิดข้อผิดพลาด เอกสารไม่มีข้อมูล"
            End Select

            btnCancel.Enabled = True
            ScriptManager.RegisterStartupScript(Me, _
                                                      Me.GetType(), _
                                                      "clientScript", _
                                                      "alert('" & reasonFail & "')", _
                                                      True)
        End If
    End Sub
End Class
